

package com.zdkj.subway.stm.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.constant.CommonConstants;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.stm.constant.StmConstans;
import com.zdkj.subway.stm.constant.StmTableCommon;
import com.zdkj.subway.stm.entity.SwStConductorSettle;
import com.zdkj.subway.stm.entity.SwStInputPassengerWork;
import com.zdkj.subway.stm.entity.SwStmStationDataEntryLog;
import com.zdkj.subway.stm.mapper.SwStInputPassengerWorkMapper;
import com.zdkj.subway.stm.service.SwStInputPassengerWorkService;
import com.zdkj.subway.stm.service.SwStmStationDataEntryLogService;
import com.zdkj.subway.stm.util.BeanUtilsStm;
import com.zdkj.subway.stm.util.LocalDateConverter;
import com.zdkj.subway.stm.util.LocalDateTimeConverter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


/**
 * 乘客事务录入主表
 *
 * @author cuilei
 * @date 2020-05-25 11:30:25
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swstinputpassengerwork")
@Api(value = "swstinputpassengerwork", tags = "乘客事务录入主表管理")
public class SwStInputPassengerWorkController {

    private final SwStInputPassengerWorkService swStInputPassengerWorkService;
    private final SwStInputPassengerWorkMapper swStInputPassengerWorkMapper;
    private final SwStmStationDataEntryLogService swStmStationDataEntryLogService;
    /**
     * 分页查询
     *
     * @param page                   分页对象
     * @param swStInputPassengerWork 乘客事务录入主表
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwStInputPassengerWorkPage(Page page, SwStInputPassengerWork swStInputPassengerWork) {

		String conductorJobNo = swStInputPassengerWork.getConductorCode();
		swStInputPassengerWork.setConductorCode(null);
		swStInputPassengerWork.setConductorName(null);


        QueryWrapper<SwStInputPassengerWork> queryWrapper = Wrappers.query(swStInputPassengerWork);
        queryWrapper.orderByDesc("WORK_DATE");

		
		if(StringUtils.isNotEmpty(swStInputPassengerWork.getSourceQueryFlag()) && StringUtils.isNotEmpty(conductorJobNo)){
            queryWrapper.lambda().eq(SwStInputPassengerWork::getConductorCode,conductorJobNo);//报表路径跳转
        }
        if(StringUtils.isEmpty(swStInputPassengerWork.getSourceQueryFlag()) && StringUtils.isNotEmpty(conductorJobNo)){
            queryWrapper.lambda().like(SwStInputPassengerWork::getConductorCode,conductorJobNo);//售票员工号模糊匹配
        }
        if (!SecurityUtils.getUser().getBelongToLine()) {
            queryWrapper.lambda().eq(SwStInputPassengerWork::getLineCode, SecurityUtils.getUser().getLineCode());
            queryWrapper.lambda().eq(SwStInputPassengerWork::getStationCode, SecurityUtils.getUser().getStationCode());
            
        }
		return R.ok(swStInputPassengerWorkService.page(page, queryWrapper));
    }

    /**
     * 根据条件查询
     * @param swStConductorSettle 根据条件查询
     * @return
     */
    @ApiOperation(value = "根据条件查询", notes = "根据条件查询")
    @GetMapping("/getpassengerwork")
    public R getSwStInputPassengerWorkPage(SwStConductorSettle swStConductorSettle) {
        SwStInputPassengerWork swStInputPassengerWork = new SwStInputPassengerWork();
        QueryWrapper<SwStInputPassengerWork> queryWrapper = Wrappers.query(swStInputPassengerWork);
        queryWrapper.lambda().eq(SwStInputPassengerWork::getLineCode, swStConductorSettle.getLineCode());
        queryWrapper.lambda().eq(SwStInputPassengerWork::getStationCode, swStConductorSettle.getStationCode());
        queryWrapper.lambda().eq(SwStInputPassengerWork::getConductorCode,swStConductorSettle.getConductorJobNo());
        queryWrapper.lambda().eq(SwStInputPassengerWork::getWorkDate,swStConductorSettle.getSettleTime());
        queryWrapper.lambda().eq(SwStInputPassengerWork::getClassNumber,swStConductorSettle.getConductorShifts());
        queryWrapper.lambda().eq(SwStInputPassengerWork::getDeviceOperateNum,swStConductorSettle.getDeviceOperateNum());
        queryWrapper.lambda().eq(SwStInputPassengerWork::getBomCode,swStConductorSettle.getBomCode());
        List<SwStInputPassengerWork> list  =  swStInputPassengerWorkService.list(queryWrapper);
        SwStInputPassengerWork sw = new SwStInputPassengerWork();
        if(CollectionUtil.isNotEmpty(list)){
            return R.ok(list.get(0));
        }else{
            return R.ok();
        }
    }

    /**
     * 通过id查询乘客事务录入主表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swStInputPassengerWorkService.getById(id));
    }



    /**
     * 通过id查询乘客事务录入主表历史记录
     *
     * @param  id
     * @return R
     */
    @ApiOperation(value = "通过id查询乘客事务录入主表历史记录", notes = "通过id查询乘客事务录入主表历史记录")
    @GetMapping("getLogById/{id}")
    public R getLogById(@PathVariable("id") Integer id) {
        SwStmStationDataEntryLog swStmStationDataEntryLog = swStmStationDataEntryLogService.getBaseMapper()
                .selectOne(Wrappers.<SwStmStationDataEntryLog>lambdaQuery()
                        .eq(SwStmStationDataEntryLog::getRelationId, id)
                        .eq(SwStmStationDataEntryLog::getLogTableName, StmTableCommon.SW_ST_INPUT_PASSENGER_WORK));
        if(swStmStationDataEntryLog != null){
            //返回json串
            return R.ok(JSONObject.parseObject(swStmStationDataEntryLog.getLogInfo()));
        }else {
            return R.failed("没有进行过报表差错更改，暂无数据！");
        }

    }

    /**
     * 新增乘客事务录入主表
     *
     * @param swStInputPassengerWork 乘客事务录入主表
     * @return R
     */
    @ApiOperation(value = "新增乘客事务录入主表", notes = "新增乘客事务录入主表")
    //@SysLog("新增乘客事务录入主表")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('stm_sw_st_input_passenger_work_add')")
    public R save(@RequestBody SwStInputPassengerWork swStInputPassengerWork) {
        SwStInputPassengerWork defaultObj = ObjectUtils.getDefaultObj(SwStInputPassengerWork.class);
        BeanUtils.copyProperties(swStInputPassengerWork, defaultObj);
        defaultObj.setBomCode(BeanUtilsStm.bomOrJobNoSort(defaultObj.getBomCode()));//bom编号排序后新增
        //设备操作号去空格
        defaultObj.setDeviceOperateNum(BeanUtilsStm.strRemoveBlank(defaultObj.getDeviceOperateNum()));
        return R.ok(swStInputPassengerWorkService.save(defaultObj));
    }

    /**
     * 修改乘客事务录入主表
     *
     * @param swStInputPassengerWork 乘客事务录入主表
     * @return R
     */
    @ApiOperation(value = "修改乘客事务录入主表", notes = "修改乘客事务录入主表")
    //@SysLog("修改乘客事务录入主表")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('stm_sw_st_input_passenger_work_edit')")
    public R updateById(@RequestBody SwStInputPassengerWork swStInputPassengerWork) {
        SwStInputPassengerWork inputPassengerWork = swStInputPassengerWorkService.getById(swStInputPassengerWork.getId());
        if(ObjectUtil.isNotEmpty(inputPassengerWork)){
            String submitStatus = inputPassengerWork.getSubmitStatus();
            if("1".equals(submitStatus)){
                return R.failed(StmConstans.failedEdit);
            }
        }
        swStInputPassengerWork.setBomCode(BeanUtilsStm.bomOrJobNoSort(swStInputPassengerWork.getBomCode()));//bom编号排序后修改
        //设备操作号去空格
        swStInputPassengerWork.setDeviceOperateNum(BeanUtilsStm.strRemoveBlank(swStInputPassengerWork.getDeviceOperateNum()));
        return R.ok(swStInputPassengerWorkService.updateById(swStInputPassengerWork));
    }

    /**
     * 通过id删除乘客事务录入主表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除乘客事务录入主表", notes = "通过id删除乘客事务录入主表")
    //@SysLog("通过id删除乘客事务录入主表")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_input_passenger_work_del')")
    public R removeById(@PathVariable Integer id) {
        SwStInputPassengerWork inputPassengerWork = swStInputPassengerWorkService.getById(id);
        if(ObjectUtil.isNotEmpty(inputPassengerWork)){
            String submitStatus = inputPassengerWork.getSubmitStatus();
            if("1".equals(submitStatus)){
                return R.failed(StmConstans.failedDelete);
            }
        }
        return R.ok(swStInputPassengerWorkService.removeById(id));
    }

    /**
     * 批量提交乘客事务数据
     *
     * @param idList
     * @return
     */
    @ApiOperation(value = "批量提交乘客事务数据", notes = "批量提交乘客事务数据")
    //@SysLog("批量提交乘客事务数据")
    @PostMapping("/submit")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_input_passenger_work_submit')")
    public R submit(@RequestBody List<Integer> idList) {
        List<SwStInputPassengerWork> submitList = new ArrayList<>();
        idList.forEach(id -> {
            SwStInputPassengerWork submitItem = new SwStInputPassengerWork();
            submitItem.setId(id);
            submitItem.setSubmitStatus(CommonConstants.SUBMIT);
            submitList.add(submitItem);
        });
        return R.ok(swStInputPassengerWorkService.updateBatchById(submitList));
    }
    /**
     * 导出乘客事务信息
     *
     * @param swStInputPassengerWork
     * @param response
     * @throws IOException
     */
    @ApiOperation(value = "导出乘客事务信息", notes = "导出乘客事务信息")
    @GetMapping("/export")
    //@SysLog("导出乘客事务信息")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_input_passenger_work_export')")
    public void exportExcel(SwStInputPassengerWork swStInputPassengerWork, HttpServletResponse response) throws IOException {
        List<SwStInputPassengerWork> swStInputPassengerWorkList = swStInputPassengerWorkService.list(Wrappers.query(swStInputPassengerWork));
        String fileName = URLEncoder.encode("乘客事务信息", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SwStInputPassengerWork.class).registerConverter(new LocalDateTimeConverter())
                .registerConverter(new LocalDateConverter()).sheet("乘客事务信息").doWrite(swStInputPassengerWorkList);
    }

    /**
     * 乘客事务录入通过被合并的数据ID查询合并之前的记录
     *
     * @param
     * @return R
     */
    @ApiOperation(value = "通过被合并的数据ID查询合并之前的记录", notes = "通过被合并的数据ID查询合并之前的记录")
    @GetMapping("getMergeBeforById/{id}")
    public R getMergeBeforById(@PathVariable("id") Integer id) {
        SwStInputPassengerWork inputPassengerWork = swStInputPassengerWorkService.getById(id);
        if(ObjectUtil.isNotEmpty(inputPassengerWork)){
            String isBeMergedId = inputPassengerWork.getIsBeMergedId();
            String[] split = isBeMergedId.split(",");
            List<SwStInputPassengerWork> list = swStInputPassengerWorkMapper.getList(split);
            return R.ok(list);
        }else {
            return R.failed("无合并数据！");
        }
    }
}
